package cn.gwm.flink.streaming.dwd.standardization;

import cn.gwm.flink.streaming.beans.dwd.DwdStandardField;
import cn.gwm.flink.streaming.constant.BusinessUrl;
import cn.gwm.utils.ConfigLoader;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName StandardPoolField
 * @Description
 * @Author LiangGuang
 * @Date 2023/05/19 20:51
 */
public class StandardPoolField {

    private static Long lastUpdateTime = DateUtil.lastMonth().getTime();
    /**
     * 7天更新一次
     */
    private static Long longTime = 7 * 24 * 60 * 60 * 1000L + RandomUtil.randomLong(200000);

    private static Map<String, List<DwdStandardField>> fieldMap = new ConcurrentHashMap<>();

    /**
     * 根据动力类型 获取标准字段
     *
     * @param customType
     * @return
     */
    public static List<DwdStandardField> getStandardField(String customType) {
        if (!fieldMap.containsKey(customType)) {
            query(customType);
        } else if (System.currentTimeMillis() - lastUpdateTime > longTime) {
            // 更新即可
            query(customType);
            lastUpdateTime = System.currentTimeMillis();
        }
        return fieldMap.get(customType);
    }

    public static void query(String customType) {
        Map<String, Object> param = new HashMap<>();
        param.put("customType", customType);
        String s = HttpUtil.get(ConfigLoader.get("charging.station.type.url") + BusinessUrl.STANDARD_FIELD_URL, param);
        JSONObject parseObj = JSONUtil.parseObj(s);
        List<DwdStandardField> list = new ArrayList<>();

        try {
            if (parseObj.getInt("code") == 200) {
                JSONArray array = parseObj.getJSONArray("data");
                if (array.size() > 0) {
                    array.forEach(item -> {
                        list.add(JSONUtil.toBean((JSONObject) item, DwdStandardField.class));
                    });
                }
            }
            fieldMap.put(customType, list);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
